#!/usr/bin/env python
# coding: utf-8

# ##  课堂学习内容
# 
# > * 1、高德API-WEB服务
# > * 2、API经济成本的预估（调用量，并发量）
# > * 3、地理编码
# ...
# ## 课后练习
# > * 1、[地理编码](http://lbs.amap.com/api/webservice/guide/api/georegeo)
# > * 2、[路径规划](http://lbs.amap.com/api/webservice/guide/api/direction)
# ...

# 

# ### 准备工作

# In[113]:


import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"


# ### 地理编码
# > * 1、结构化地址的定义：首先，地址肯定是一串字符，内含国家、省份、城市、区县、城镇、乡村、街道、门牌号码、屋邨、大厦等建筑物名称。按照由大区域名称到小区域名称组合在一起的字符。一个有效的地址应该是独一无二的。注意：针对大陆、港、澳地区的地理编码转换时可以将国家信息选择性的忽略，但省、市、城镇等级别的地址构成是不能忽略的。暂时不支持返回台湾省的详细地址信息。
# > * 2、url:https://restapi.amap.com/v3/geocode/geo?parameters
# > * 3、requests.get()
# > * 4、参数
# >> * A.必选:key（高德API秘钥），address(结构化地址)
# >> * B.可选:city(指定查询的城市),batch(批量查询控制)

# In[114]:


#### 准备数据 请思考高德API是怎么样获取数据的？——数据库查询
中大南方_address = "广东省广州市中山大学南方学院"


# In[115]:


def geocode(key,address,city=None,batch=None,)->str:
    """获取高德API的地理编码""" 
url = "https://restapi.amap.com/v3/geocode/geo?parameters"
params = {
    "key":xing_key,
    "address":中大南方_address
}
response = requests.get(url,params=params)
response


# In[116]:


response.json()


# In[117]:


中大南方_location = response.json()["geocodes"][0]['location']
中大南方_location


# In[118]:


### 小结


# ### 逆地理编码
# > * A.url:https://restapi.amap.com/v3/geocode/regeo?parameters
# > * B.requests.get()
# > * C.参数:
# >> * 1、必选：key，location（经纬度坐标）
# >> * 2、可选：extensions(返回结果控制)默认值为base,radius(搜索半径)

# In[119]:


# 数据准备 中大南方_location


# In[120]:


def regeo(key,location,extensions="base",radius=None,):
    """获取高德API的地理编码"""
    url = 'https://restapi.amap.com/v3/geocode/regeo?parameters'
    params = {'key':key,
          'location':location,
          'extensions':extensions,
             'radius':radius
}
    r = requests.get(url,params)
    results = r.json
    return results


# In[121]:


url = 'https://restapi.amap.com/v3/geocode/regeo?parameters'
params = {
    'key':xing_key,
    'location':中大南方_location,
    'extensions':'all'
}
r = requests.get(url,params)


# In[122]:


r


# In[123]:


r.json()


# In[124]:


import json
_roads_ = []
for item in r.json()['regeocode']['roads']:
    _roads_.append(item['name'])
_roads_


# In[125]:


pd.json_normalize(r.json()['regeocode']['roads'])


# In[126]:


pd.json_normalize(r.json()['regeocode']['pois'])


# In[127]:


pd.json_normalize(r.json()['regeocode']['aois'])


# In[ ]:


### 小结



# ### 路径规划
# > * 1、步行
# > * 2、公交车
# > * 3、驾车
# 

# #### 步行
# > * 1、url:https://restapi.amap.com/v3/direction/walking?parameters
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key，origin（出发点），destination（目的地）
# >> * B.可选：sig(数字签名)

# In[128]:


# 数据准备
origin = "广东省广州市中山大学南方学院"
destination = "广州市从化区龙岗"


# In[129]:


# 思考：如果有1000个位置？重复代码？
# 函数！ -->1、接受代码，重复利用 2、可以给小白（会一点Python）用
# 地理编码 =》 函数形式
# 函数不会报错，哪怕你写的语法有错误，哪怕你写的参数没定义？----》 函数只有在执行的时候才会真正意义的运行
def geocode(key,address,city=None,batch=None,sig=None) -> str:
    """获取高德API的地理编码
    注释：key是指高德API的秘钥，请先去注册
    address使指结构化地址，具体请查看：http://lbs.amap.com/api/webservice/guide/api/georegeo
    """
    url = "https://restapi.amap.com/v3/geocode/geo?parameters"
    params = {
        "key":key,
        "address":address
    }
    response = requests.get(url,params=params)
    results = response.json()["geocodes"][0]['location']
    # 返回值
    return results


# In[130]:


help(geocode)


# In[131]:


起始点_中大南方 = geocode(xing_key,origin)
起始点_中大南方


# In[132]:


目的地_龙岗 = geocode(xing_key,destination)
目的地_龙岗


# In[133]:


# 步行
url = "https://restapi.amap.com/v3/direction/walking?parameters"
params = {
    "key":xing_key,
    "origin":起始点_中大南方,
    "destination":目的地_龙岗
}
r = requests.get(url,params)
r


# In[134]:


r.json()


# In[136]:


r.json()['route']['paths']


# In[137]:


pd.json_normalize(r.json()['route']['paths'][0]['steps'])


# In[ ]:


### 小结



# #### 公交车
# > * 1、url:	https://restapi.amap.com/v3/direction/transit/integrated?parameters
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key，origin（出发点），destination（目的地),city
# >> * B.可选：cityd(跨城必填)

# In[141]:


# 数据准备
xing_key = "09f941d0953f18dc75c9742d60200a79"
origin = "广东省广州市天河区暨南大学"
destination = "广东省广州市海珠区广州塔"


# In[142]:


import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"
city = "广东省"


# In[143]:


def geocode(key,address,city=None,batch=None,extensions="base")->str:
    """获取高德API的地理编码"""    
    url = "https://restapi.amap.com/v3/geocode/geo?parameters"
    params = {
        "key":key,
        "address":address,
        "city":city,
        "batch":batch,
        "extensions":extensions
        
    }
    response = requests.get(url,params = params)
    results = response.json()
    return results


# In[144]:


起始点_暨南大学 = geocode(xing_key,origin)['geocodes'][0]['location']
起始点_暨南大学


# In[145]:


目的地_广州塔 = geocode(xing_key,destination)['geocodes'][0]['location']
目的地_广州塔


# In[146]:


url = 'https://restapi.amap.com/v3/direction/transit/integrated?parameters'
params = {'key':xing_key,
          'origin':起始点_暨南大学,
          'destination':目的地_广州塔,
          'city':city,
          'extensions':all
          }
r = requests.get(url,params)
r.json()


# In[147]:


r.json()['route']['transits']


# In[148]:


pd.json_normalize(r.json()['route']['transits'])


# In[ ]:


### 小结


# #### 驾车
# > * 1、url: https://restapi.amap.com/v3/direction/driving?parameters
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key，origin（出发点），destination（目的地)
# >> * B.可选：originid(出发点poiid),strategy(驾车选择策略),waypoints(途经点)

# In[149]:


# 数据准备
xing_key = "09f941d0953f18dc75c9742d60200a79"
origin = "广东省广州市从化区中山大学南方学院"
destination = "广东省广州市番禺区长隆欢乐世界"


# In[150]:


import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[153]:


def geocode(key,address,originid=None,strategy=None,waypoints=None)->str:
    """获取高德API的地理编码"""    
    url = "https://restapi.amap.com/v3/geocode/geo?parameters"
    params = {
        "key":key,
        "address":address,
        "originid":originid,
        "strategy":strategy
        
    }
    response = requests.get(url,params = params)
    results = response.json()
    return results


# In[154]:


起始点_中山大学南方学院 = geocode(xing_key,origin)['geocodes'][0]['location']
起始点_中山大学南方学院


# In[155]:


目的地_长隆欢乐世界 = geocode(xing_key,destination)['geocodes'][0]['location']
目的地_长隆欢乐世界


# In[156]:


url = 'https://restapi.amap.com/v3/direction/driving?parameters'
params = {'key':xing_key,
          'origin':起始点_中山大学南方学院,
          'destination':目的地_长隆欢乐世界
          }
r = requests.get(url,params)
r.json()


# In[168]:


r.json()['route']['paths'][0]['steps']


# In[171]:


pd.json_normalize(r.json()['route']['paths'][0]['steps'])


# In[172]:


###小结


# In[ ]:





# ### 行政区域查询
# > * 1、url: https://restapi.amap.com/v3/config/district?parameters
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key
# >> * B.可选：keywords(查询关键字),page(需要第几页数据)默认数值为1,subdistrict(子级行政区),extensions(返回结果控制)默认数值为base

# In[182]:


# 数据准备
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[3]:


import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"
keywords = "四川"
subdistrict="2"


# In[4]:


def geocode(key,keywords="四川",subdistrict="2",page="1",extensions="base")->str:
    """获取高德API的地理编码"""    
    url = "https://restapi.amap.com/v3/geocode/geo?parameters"
    params = {
        "key":key,
        "keywords":keywords,
        "subdistrict":subdistrict,
        "page":page,
        "extensions":extensions
        
    }
    response = requests.get(url,params = params)
    results = response.json()
    return results


# In[5]:


url = 'https://restapi.amap.com/v3/config/district?parameters'
params = {'key':xing_key,
          'keywords':"四川",
          'extensions':"all",
          'subdistrict':subdistrict
          }
r = requests.get(url,params)
r.json()


# In[ ]:





# In[ ]:





# In[ ]:





# ### 搜索POI
# > * 1、关键字搜索
# > * 2、周边搜索
# > * 3、边形搜索
# > * 4、ID查询

# #### 关键字搜索
# > * 1、url: 	https://restapi.amap.com/v3/place/text?parameters
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key，keywords(keywords和types两者至少必选其一)，types(keywords和types两者至少必选其一)
# >> * B.可选：city(查询城市),children(是否按照层级展示子POI数据,可选值：children=1),extensions(返回结果控制)默认数值为base

# In[1]:


# 数据准备
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[2]:


import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"
keywords = "大北街小学"
city = "四川"


# In[6]:


def geocode(key,keywords="大北街小学",city="四川",children="1",extensions="base")->str:
    """获取高德API的地理编码"""    
    url = "https://restapi.amap.com/v3/geocode/geo?parameters"
    params = {
        "key":key,
        "keywords":keywords,
        "city":city,
        "children":children,
        "extensions":extensions
        
    }
    response = requests.get(url,params = params)
    results = response.json()
    return results


# In[10]:


url = 'https://restapi.amap.com/v3/place/text?parameters'
params = {'key':xing_key,
          'keywords':"大北街小学",
          'city':'四川',
          'extensions':"base",
          'children':"1"
          }
r = requests.get(url,params)
r.json()


# In[ ]:





# #### 周边搜索
# > * 1、url:	https://restapi.amap.com/v3/place/around?parameters 
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key,location(中心点坐标)
# >> * B.可选：keywords(查询关键字),types(查询POI类型),city(查询城市),extensions(返回结果控制)默认数值为base

# In[42]:


# 数据准备
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[80]:


import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"
location = "汕头大学"
city = "广东"


# In[81]:


def geocode(key,address,keywords=None,city="广东",extensions="base",types=None) -> str:
    """获取高德API的地理编码"""
    url = "https://restapi.amap.com/v3/geocode/geo?parameters"
    params = {
        "key":xing_key,
        "address":address,
        "keywords":keywords,
        "types":types,
        "city":city,
        "extensions":extensions
    }
    
    response = requests.get(url,params = params)
    results = response.json()
    return results


# In[82]:


中心点坐标 = geocode(xing_key,location)
中心点坐标


# In[83]:


url = 'https://restapi.amap.com/v3/place/text?parameters'
params = {'key':xing_key,
          'location':"116.631809,23.412536",
          'keywords':"汕头大学",
          'city':'广东',
          'extensions':"base"
          }
r = requests.get(url,params)
r.json()


# In[ ]:





# In[ ]:





# #### 多边形搜索
# > * 1、url: https://restapi.amap.com/v3/place/polygon?parameters 
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key,polygon(经纬度坐标对)
# >> * B.可选：keywords(查询关键字),types(查询POI类型),offset(每页记录数据),extensions(返回结果控制)默认数值为base

# In[19]:


### 数据准备
import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[16]:


def poly(key,polygon,keywords=None,types=None,offset='20',page='1',extensions='base',sig=None,output='json',callback=None):
    #多边形搜索
    url='https://restapi.amap.com/v3/place/polygon?parameters '
    params={
        'key':xing_key,
        'polygon':polygon,
        'keywords':keywords,
        'types':types,
        'offset':offset,
        'page':page,
        'extensions':extensions,
        'sig':sig,
        'output':output,
        'callback':callback     
    }
    response=requests.get(url,params)
    results=response.json()
    # return
    return results


# In[18]:


polygon='116.460988,40.006919|116.48231,40.007381;116.47516,39.99713|116.472596,39.985227|116.45669,39.984989|116.460988,40.006919'
poly(xing_key,polygon,keywords=None,types=None,offset='20',page='1',extensions='base',sig=None,output='json',callback=None)


# In[ ]:





# #### ID查询
# > * 1、url: https://restapi.amap.com/v3/place/detail?parameters  
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key,id(兴趣点ID)
# >> * B.可选：sig(数字签名),callback(回调函数)

# In[21]:


### 数据准备
import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[22]:


def detail(id):
    #id查询搜索
    url='https://restapi.amap.com/v3/place/polygon?parameters '
    key='18ef7dd6aeefc21dade574262c00f213'
    params={
        'key':xing_key,
        'id':id
    }
    response=requests.get(url,params)
    results=response.json()
    # return
    return results


# In[23]:


id=''
detail(id)


# In[ ]:





# ### IP定位
# > * 1、url: https://restapi.amap.com/v3/ip?parameters
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key
# >> * B.可选：ip(ip地址),sig(签名),output(返回格式)

# In[24]:


### 数据准备
import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[25]:


def geocode(key,ip=None,sig=None,output=None) -> str:
    """获取高德API的地理编码"""
    url = "https://restapi.amap.com/v3/geocode/geo?parameters"
    params = {
        "key":xing_key,
        "ip":ip,
        "sig":sig,
        "output":output
    }
    
    response = requests.get(url,params = params)
    results = response.json()
    return results


# In[26]:


url = 'https://restapi.amap.com/v3/ip?parameters'
params = {'key':xing_key
          }
r = requests.get(url,params)
r.json()


# In[ ]:





# In[ ]:





# In[ ]:





# ### 批量请求接口

# In[27]:


import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[14]:


def reqs():
    url="https://restapi.amap.com/v3/batch?key=<09f941d0953f18dc75c9742d60200a79>"
    params={
    "ops": [{"url": "/v3/place/around?offset=10&page=1&key=<09f941d0953f18dc75c9742d60200a79>&location=116.50394379585519,39.278209477408794&output=json&radius=100000&types=080000"
        },
        {"url": "/v3/place/around?offset=10&page=1&key=<09f941d0953f18dc75c9742d60200a79>&location=118.50394379585519,39.278209477408794&output=json&radius=100000&types=080000"
        }
        ]
        }
    response=requests.get(url,params=params)
    r = response.json()
    return r


# In[16]:


url="https://restapi.amap.com/v3/batch?key=<09f941d0953f18dc75c9742d60200a79>"
params={
"ops": [{"url": "/v3/place/around?offset=10&page=1&key=<09f941d0953f18dc75c9742d60200a79>&location=116.50394379585519,39.278209477408794&output=json&radius=100000&types=080000"
    },
    {"url": "/v3/place/around?offset=10&page=1&key=<09f941d0953f18dc75c9742d60200a79>&location=118.50394379585519,39.278209477408794&output=json&radius=100000&types=080000"
    }
    ]
    }
r = requests.get(url,params)
r.json()


# In[ ]:





# In[ ]:





# ### 静态地图
# > * 1、https://restapi.amap.com/v3/staticmap?parameters
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key,location(地图中心点,部分条件必填),zoom(地图级别)
# >> * B.可选：size(地图大小,默认400*400),scale(普通/高清,默认为1),markers(标注),labels(标签),paths(折线),traffic(交通路况标识,默认为0),sig(数字签名)

# In[28]:


### 数据准备
import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[29]:


def amap(key,location,zoom,size='400*400',scale='1',markers=None,labels=None,paths=None,traffic='0',sig=None):
    #获取静态地图信息
    url='https://restapi.amap.com/v3/staticmap?parameters'
    params={
    'key':xing_key,
    'location':location,
    'zoom':zoom,
    'scale':scale,
    'markers':markers,
    'labels':labels,
    'paths':paths,
    'traffic':traffic,
    'sig':sig
    }
    r=requests.get(url,params)
    data=r.url
    return data


# In[34]:


location='113.679262,23.632583'
zoom='15'
amap(xing_key,location,zoom,size='400*400',scale='1',markers=None,labels=None,paths=None,traffic=None,sig=None)


# In[ ]:





# In[ ]:





# ### 坐标转换
# > * 1、https://restapi.amap.com/v3/assistant/coordinate/convert?parameters
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key,location(坐标点)
# >> * B.可选：coordsys(原坐标系,默认值autonavi),sig(数字签名),output(返回数据格式类型,默认值JSON)
# 
# 

# In[1]:


### 数据准备
import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[2]:


def convert(key,locations,coordays='',sig='',output=''):
    url='https://restapi.amap.com/v3/assistant/coordinate/convert?parameters'
    params={
        'key':xing_key,
        "locations":locations,
        'coordays':coordays,
        'sig':sig,
        'output':output
    }
    response=requests.get(url,params)
    r=response.json()
    return r


# In[3]:


locations='116.481499,39.990475|116.481499,39.990375'
convert(xing_key,locations,coordays='',sig='',output='')


# In[ ]:





# In[ ]:





# ### 天气查询
# > * 1、https://restapi.amap.com/v3/weather/weatherInfo?parameters
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key,city(城市编码)
# >> * B.可选：extensions(气象类型),output(返回数据格式类型,默认值JSON)
# 

# In[4]:


### 数据准备
import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[5]:


def weather(key,city,extensions='base',output=''):
    # 天气查询
    url='https://restapi.amap.com/v3/weather/weatherInfo?parameters'
    params={
        'key':xing_key,
       'city':city,
        'extensions':extensions,
        'output':output
    }
    response=requests.get(url,params)
    r=response.json()
    return r


# In[9]:


city='510500'
weather(xing_key,city,extensions='base',output='')


# In[ ]:





# In[ ]:





# ### 输入提示
# > * 1、https://restapi.amap.com/v3/assistant/inputtips?parameters
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key,keywords(查询关键词)
# >> * B.可选：type(POI分类),location(坐标),city(搜索城市,可选值：citycode、adcode，不支持县级市),citylimit(仅返回指定城市数据),datatype(返回的数据类型),sig(数字签名),callback(回调函数),output(返回数据格式类型,默认值JSON)
# 

# In[10]:


### 数据准备
import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[12]:


def input(key,keywords,type=None,location=None,city=None,
          citylimit='false',datatype=None,sig=None,output='json',callback=None):
    # 输入提示
    url='https://restapi.amap.com/v3/assistant/inputtips?parameters'
    params={
        'key':xing_key,
        'keywords':keywords,
        'type':type,
        'location':location,
        'city':city,
        'citylimit':citylimit,
        'datatype':datatype,
        'sig':sig,
        'output':output,
        'callback':callback
    }
    response=requests.get(url,params)
    r=response.json()
    return r


# In[13]:


keywords='大北街小学'
input(xing_key,keywords,type=None,location=None,city=None,citylimit='false',datatype=None,sig=None,output='json',callback=None)


# In[ ]:





# ### 输入提示
# > * 1、https://restapi.amap.com/v3/traffic/status/rectangle?parameters
# > * 2、requests.get()
# > * 3、参数：
# 
# >> * A.必选：key
# >> * B.可选：level(道路等级,默认为5),extensions(返回结果控制,默认值为base),sig(数字签名),callback(回调函数),output(返回数据格式类型,默认值JSON),rectangle(代表此为矩形区域查询)
# 

# In[14]:


### 数据准备
import requests,json
import pandas as pd
xing_key = "09f941d0953f18dc75c9742d60200a79"


# In[15]:


def traffic(key,rectangle,level='5',extensions='base',sig=None,output='json',callback=None):
    url='https://restapi.amap.com/v3/traffic/status/rectangle?parameters'
    params={
        'key':xing_key,
        'rectangle':rectangle,
        'level':level,
        'extensions':extensions,
        'sig':sig,
        'output':output,
        'callback':callback,
    }
    response=requests.get(url,params)
    r=response.json()
    return r


# In[16]:


rectangle='116.351147,39.966309;116.357134,39.968727'
traffic(xing_key,rectangle,level='5',extensions='base',sig=None,output='json',callback=None)


# In[ ]:




